import urllib3
import json
http=urllib3.PoolManager()
# response=http.request('GET','http://www.baidu.com')
# print(response.data.decode('utf-8'))
# print(response.status)
# print(response.getheaders())
# print(response.getheader('Content-Length'))

# form 数据
postResponse=http.request('POST',"http://httpbin.org/post",fields={'name':'张三'.encode('utf-8')})
data=json.loads(postResponse.data.decode('utf-8'))
#json数据
rdata={"name":"张三"}
encode_rdata=json.dumps(rdata).encode('utf-8')
#异常处理: 示例是超时
try:
    postResponse=http.request(
        'POST',
        "http://httpbin.org/post",
        body=encode_rdata,
        headers={'Content-Type':'application/json'},
        timeout=1   #单位秒
    )
    print(json.loads(postResponse.data.decode('utf-8'))['json'])
except urllib3.exceptions.ReadTimeoutError as e:
    print('TIME OUT')

#---------------验证--------------------------

#身份认证 Basic_Auth，构造头
heads=urllib3.make_headers(basic_auth='xuchang:123')
response=http.request('GET','http://httpbin.org/basic-auth/xuchang/123',headers=heads)   #利用httpbin建立一个 username=xuchang ,password=123的basic_auth。
print(response.data.decode('utf-8'))


#---------------代理-------------------------

# http=urllib3.ProxyManager('http://125.46.0.62:53281/')
# heads={'user-agent':'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14'}
# response=http.request('GET','http://httpbin.org/user-agent',headers=heads)
# print(response.data.decode('utf-8'))

# -----------------Cookie(urllib3支持较弱) -------------------

# print(response.getheaders())
# response=http.request('GET','http://httpbin.org/cookies',headers={'Cookie':'123'})
# print(response.data.decode('utf-8'))

# -----------------二进制文件-----------------
http=urllib3.PoolManager()
r=http.request('GET','https://github.com/favicon.ico') 
with open('E:/test.ico','wb') as f:     #wb代表二进制打开文件
    f.write(r.data)
